package pay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import pay.commont.*;
import pay.dao.*;
import pay.entity.*;
import pay.service.MessageService;
import pay.utils.MessageUtils;

import java.text.SimpleDateFormat;
import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Autowired
    private OrderGoodMapper orderGoodMapper;

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private GoodMapper goodMapper;

    @Resource
    private AuthenticatedGameDao authenticatedGameDao;

    @Resource
    private ContestItemMapper contestItemMapper;

    @Resource
    private ContestItemUserMapper contestItemUserMapper;

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private SettingDictMapper settingDictMapper;

    @Value("${message.template.game:message_template_game}")
    private String messageTemplateGameName;

    @Value("${message.template.activate:message_template_activate}")
    private String messageTemplateActivateName;

    @Value("${message.template.post.place:message_template_post_place}")
    private String messageTemplatePostPlaceName;

    @Autowired
    MessageUtils messageUtils;

    public void sendMessageToUser(MessageEntity message) {
        int result = messageMapper.insert(message);
        if (result <= 0) {
            throw new RuntimeException("系统内部错误");
        }
    }

    @Override
    public void paySuccessSendMessage(OrdersEntity order) {
        List<GoodsEntity> goods = goodMapper.selectAllByOrderId(order.getId());
        for (GoodsEntity good : goods) {
            GoodsType goodsType = GoodsType.getGoodsType(good.getGoodsType());
            switch (goodsType) {
                case GAME:
                    sendGameMessage(order, good);
                    break;
                case ADDITION:
                    // 购买增值服务包 - 暂时不处理
                    break;
                case VIP:
                    sendVipMessage(order);
                    break;
                case POST:
                    sendPostMessage(order);
                    break;
                case ACTIVATE:
                case CLUB_ACTIVATE:
                case SPACE:
                    // 其他类型暂时不处理
                    log.debug("订单 {} 的商品类型 {} 暂不处理消息发送", order.getId(), goodsType.getDesc());
                    break;
                default:
                    log.warn("未知的商品类型: {}", good.getGoodsType());
                    break;
            }
        }
    }

    private void sendGameMessage(OrdersEntity order, GoodsEntity good) {
        // 获取报名单
        ContestItemUserEntity contestItemUser = contestItemUserMapper.selectById(order.getReservationId());
        if (contestItemUser == null) {
            log.error("订单 {} 对应的比赛报名单不存在", order.getId());
            return;
        }

        ContestItemEntity contestItem = contestItemMapper.selectById(contestItemUser.getContestItemId());
        if (contestItem == null) {
            log.error("订单 {} 对应的比赛项目不存在", order.getId());
            return;
        }

        AuthenticatedGameEntity game = authenticatedGameDao.selectById(contestItem.getMainId());
        if (game == null) {
            log.error("订单 {} 对应的比赛不存在", order.getId());
            return;
        }

        // 特殊处理ID为94的比赛
        if (game.getId() == 94) {
            String content = String.format(
                    "<p>您已成功报名安琪杯·最美南岸城市定向赛<strong>%s</strong>组别，活动时间2025年10月18日13:00，赛事包领取时间2025年10月16日14:00-18:00，10月17日16:00-21:00。</p>",
                    contestItem.getName()
            );

            MessageEntity message = new MessageEntity();
            message.setUserId(order.getUserId());
            message.setTitle("报名成功");
            message.setContent(content);
            message.setBindingId(order.getId());
            message.setType(MessageType.SYSTEM.getCode());
            message.setBindingType(MessageBindingType.ORDER.getCode());
            sendMessageToUser(message);
        } else {
            sendRegularGameMessage(order, contestItem, game);
        }
    }

    private void sendRegularGameMessage(OrdersEntity order, ContestItemEntity contestItem, AuthenticatedGameEntity game) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH:mm");
        String formattedDate = dateFormat.format(game.getGameStart());

        String content;
        Integer templateId = null;

        if (game.getAuthType() == AuthGameType.PLATFORM_ACTIVITY.getCode()) {
            content = String.format(
                    "您已报名参加%s，报名赛项%s，活动将于%s开始，活动地点：%s。报名信息可以在【我的活动】中查看。期待您的精彩表现！Move，动就对了！",
                    game.getOnlyName(),
                    contestItem.getName(),
                    formattedDate,
                    game.getAddress()
            );
            templateId = getTemplateId(messageTemplateActivateName);
        } else if (game.getAuthType() == AuthGameType.AUTH_GAME.getCode()) {
            content = String.format(
                    "您已报名参加%s，报名赛项%s，比赛将于%s开始，比赛地点：%s。期待您的精彩表现！Move，动就对了！",
                    game.getOnlyName(),
                    contestItem.getName(),
                    formattedDate,
                    game.getAddress()
            );
            templateId = getTemplateId(messageTemplateGameName);
        } else {
            log.warn("未知的认证类型: {}", game.getAuthType());
            return;
        }

        MessageEntity message = new MessageEntity();
        message.setUserId(order.getUserId());
        message.setTitle("报名成功");
        message.setContent(content);
        message.setBindingId(order.getId());
        message.setType(MessageType.SYSTEM.getCode());
        message.setBindingType(MessageBindingType.ORDER.getCode());
        if (templateId != null) {
            message.setTemplateId(templateId);
        }
        sendMessageToUser(message);
    }

    private void sendVipMessage(OrdersEntity order) {
        MessageEntity message = new MessageEntity();
        message.setUserId(order.getUserId());
        message.setTitle("充值成功");
        message.setContent("恭喜您成为Move友会员，您的会员权益如下：①每月一张平台赛事8折优惠券；②首页5个装备展示栏；③排行榜完整榜单查阅权限；④个人主页6个Tag展示栏。快来体验吧！");
        message.setBindingId(order.getId());
        message.setType(MessageType.SYSTEM.getCode());
        sendMessageToUser(message);
    }

    private void sendPostMessage(OrdersEntity order) {
        AddressEntity addressEntity = addressMapper.selectById(order.getAddressId());
        if (addressEntity == null) {
            log.error("订单 {} 对应的地址不存在", order.getId());
            return;
        }

        String goodsName = messageUtils.getPostOrderGoodsNameFormat(order, orderGoodMapper, goodMapper);
        String content = String.format(
                "<p>您购买的<strong>%s</strong>已为您创建邮寄订单</p><p>收件信息如下：<strong>【收件人：%s】【联系方式：%s】【地址：%s</strong>】。</p><p>商品将于3-7日内寄出，请您关注通知消息中的物流信息。如收件信息有误，请联系Move小助理。</p>",
                goodsName,
                addressEntity.getName(),
                addressEntity.getPhone(),
                addressEntity.getProvince() + addressEntity.getCity() + addressEntity.getDistrict() + addressEntity.getAddress()
        );

        MessageEntity message = new MessageEntity();
        message.setUserId(order.getUserId());
        message.setTitle("商品打包中");
        message.setContent(content);
        message.setBindingId(order.getId());
        message.setType(MessageType.POST.getCode());
        message.setBindingType(MessageBindingType.ORDER.getCode());

        Integer templateId = getTemplateId(messageTemplatePostPlaceName);
        if (templateId != null) {
            message.setTemplateId(templateId);
        }

        sendMessageToUser(message);
    }

    private Integer getTemplateId(String templateKey) {
        try {
            SettingDict setting = settingDictMapper.selectOne(new QueryWrapper<SettingDict>().eq("`key`", templateKey));
            return setting != null && setting.getValue() != null ?
                    Integer.valueOf(setting.getValue()) : null;
        } catch (NumberFormatException e) {
            log.error("模板ID转换失败，key: {}", templateKey, e);
            return null;
        }
    }

    @Override
    public void vipCouponSendMessage(String userId) {
        MessageEntity message = new MessageEntity();
        message.setUserId(userId);
        message.setTitle("会员权益");
        message.setContent("亲爱的Move友会员，您的本月的平台赛事优惠券已发放，请在<我的卡包>中查看！Move，动就对了！");
        message.setType(MessageType.SYSTEM.getCode());
        sendMessageToUser(message);
    }

}